<template>
  <div class="signup-page mx-auto p-3 w-330">
    <h5 class="my-4 text-center">修改平台账户</h5>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">邮箱地址</label>
        <validate-input
          :rules="emailRules" v-model="formData.email"
          placeholder="请输入邮箱地址"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">昵称</label>
        <validate-input
          :rules="nameRules" v-model="formData.nickName"
          placeholder="请输入昵称"
          type="text"
        />
      </div>
      <template #submit>
        <button type="submit" class="btn btn-primary btn-block btn-large">确定</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'
import { useStore } from 'vuex'
import { GlobalDataProps } from '../store'
export default defineComponent({
  name: 'Signup',
  components: {
    ValidateInput,
    ValidateForm
  },
  setup () {
    const store = useStore<GlobalDataProps>()
    const currentUser:any = computed(() => store.state.user).value
    const formData = reactive({
      email: currentUser.email,
      nickName: currentUser.nickName
    })
    const store1 = useStore()
    const route = useRoute()
    const router = useRouter()
    const emailRules: RulesProp = [
      { type: 'required', message: '电子邮箱地址不能为空' },
      { type: 'email', message: '请输入正确的电子邮箱格式' }
    ]
    const nameRules: RulesProp = [
      { type: 'required', message: '昵称不能为空' }
    ]
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const payload = {
          email: formData.email,
          nickName: formData.nickName,
          createdAt: new Date().toString(),
          avatar: currentUser.avatar,
          column: currentUser.column,
          description: currentUser.description
        }
        const id = currentUser._id
        store1.dispatch('updateUserInfo', { id, payload }).then(data => {
          console.log(data.data, 'data.data')
          if (data.data) {
            store.commit('updateUser', data)
            console.log(data, 'data')
            createMessage('修改成功 2秒后跳转首页', 'success', 2000)
            setTimeout(() => {
              router.push('/login')
            }, 2000)
          }
        })
      }
    }
    return {
      emailRules,
      nameRules,
      onFormSubmit,
      formData,
      currentUser
    }
  }
})
</script>

<style>
.w-330 {
  max-width: 330px;
}
</style>
